package com.sk.weichat.ui.me.wallet;

import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ClickableSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sk.weichat.R;
import com.sk.weichat.alipay.AliPayHelper;
import com.sk.weichat.alipay.PayResult;
import com.sk.weichat.bean.OrderBean;
import com.sk.weichat.ui.WebAgreementActivity;
import com.sk.weichat.ui.base.BaseActivity;

import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.ViewPiexlUtil;
import com.sk.weichat.view.MaxValueInputFilter;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;


import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

public class RechargeActivity extends BaseActivity implements View.OnClickListener {

    private EditText edtMoney;
    private Button btnRecharge;
    private TextView tvAlipay;
    private ImageView ivClear;
    public final static String event_recharge_success = "event_recharge_success";
    private MutableLiveData<PayResult> alipayResult = new MutableLiveData<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);
        initview();
        //弹出键盘输入
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    private void initview() {
        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText(getString(R.string.title_recharge));
        findViewById(R.id.iv_title_left).setOnClickListener(this);
        TextView tvContract = findViewById(R.id.tv_contract);
        SpannableString spannableString = new SpannableString(getString(R.string.wallet_contract));
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                goToWeb(coreManager.getConfig().WALLET_CONTRACT);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.deep_purple));
                ds.setUnderlineText(false);
                ds.clearShadowLayer();
            }
        };
        spannableString.setSpan(clickableSpan, 7, spannableString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tvContract.setMovementMethod(LinkMovementMethod.getInstance());
        tvContract.setText(spannableString);
        tvContract.setHighlightColor(getResources().getColor(android.R.color.transparent));//方法重新设置文字背景为透明色。
        tvAlipay = findViewById(R.id.tv_pay_by_alipay);
        tvAlipay.setOnClickListener(this);
        ivClear = findViewById(R.id.iv_clear);
        ivClear.setOnClickListener(this);

        btnRecharge = findViewById(R.id.btn_recharge);
        btnRecharge.setOnClickListener(this);
        edtMoney = findViewById(R.id.edt_money);
        //限制最大输入
        MaxValueInputFilter maxValueInputFilter = new MaxValueInputFilter();
        maxValueInputFilter.setOnMaxValueInputListener(new MaxValueInputFilter.OnMaxValueInputListener() {
            @Override
            public void onAllowed() {

            }

            @Override
            public void onBaned() {
                //超出限制
                ToastUtil.showToast(mContext, getString(R.string.recharge_limit_toast));
            }

            @Override
            public void onIlegal() {

            }
        });
        maxValueInputFilter.setMaxValue(5000);
        edtMoney.setFilters(new InputFilter[]{maxValueInputFilter});
        edtMoney.addTextChangedListener(new TextWatcher() {
            boolean once = true;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s) && once) {
                    once = false;
                    ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) edtMoney.getLayoutParams();
                    lp.bottomMargin = ViewPiexlUtil.dp2px(mContext, 19);
                    edtMoney.setLayoutParams(lp);
                    setEditTextTextSize(edtMoney, s.toString(), 40);
                } else if (TextUtils.isEmpty(s)) {
                    ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) edtMoney.getLayoutParams();
                    lp.bottomMargin = ViewPiexlUtil.dp2px(mContext, 29);
                    edtMoney.setLayoutParams(lp);
                } else {
                    once = true;
                }
                if (TextUtils.isEmpty(s.toString())) {
                    btnRecharge.setEnabled(false);
                    btnRecharge.setBackgroundResource(R.drawable.shape_corner_26_solid_gray_bdc2c8);
                    ivClear.setVisibility(View.GONE);
                } else {
                    btnRecharge.setEnabled(true);
                    btnRecharge.setBackgroundResource(R.drawable.shape_corner_26dp_solid_primary);
                    ivClear.setVisibility(View.VISIBLE);
                }
            }
        });
        //重新设置hint字体大小
        setEditTextHintSize(edtMoney, getString(R.string.recharge_limit), 20);

        alipayResult.observe(this, new Observer<PayResult>() {
            @Override
            public void onChanged(@Nullable PayResult payResult) {
                if (payResult.isResultFlag()) {
                    EventBus.getDefault().post(event_recharge_success);
                    //支付成功
                    ToastUtil.showToast(mContext, getString(R.string.pay_success));
                    finish();
                } else {
                    //失败
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.btn_recharge:
                //充值
                float money = 0;
                try {
                    money = Float.valueOf(edtMoney.getText().toString());
                    if (money == 0f) {
                        ToastUtil.showToast(mContext, getString(R.string.recharge_limit_toast));
                        return;
                    }
                    addOrder(money, coreManager.getSelfStatus().accessToken);
                } catch (Exception e) {

                }
                break;

            case R.id.tv_pay_by_alipay:
                //支付宝支付
//                int size = ViewPiexlUtil.dp2px(mContext, 16);
//                Boolean select = (Boolean) tvAlipay.getTag();
//                if (select == null || !select) {
//                    tvAlipay.setTag(true);
//                    Drawable drawableRight = getResources().getDrawable(R.mipmap.icon_checked);
//                    drawableRight.setBounds(0, 0, size, size);
//                    tvAlipay.setCompoundDrawables(tvAlipay.getCompoundDrawables()[0], null, drawableRight, null);
//                } else {
//                    tvAlipay.setTag(false);
//                    Drawable drawableRight = getResources().getDrawable(R.drawable.ic_unchecked);
//                    drawableRight.setBounds(0, 0, size, size);
//                    tvAlipay.setCompoundDrawables(tvAlipay.getCompoundDrawables()[0], null, drawableRight, null);
//                }
                break;
            case R.id.tv_contract:
                //协议

                break;

            case R.id.iv_clear:
                edtMoney.setText("");
                break;
        }
    }

    private void goToWeb(String url) {
        Intent intent = new Intent(mContext, WebAgreementActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    //下订单
    private void addOrder(float money, String accessToken) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", accessToken);
        params.put("price", money + "");
        HttpUtils.post().url(coreManager.getConfig().ALIPAY_ORDER)
                .params(params)
                .build()
                .execute(new BaseCallback<OrderBean>(OrderBean.class) {

                    @Override
                    public void onResponse(ObjectResult<OrderBean> result) {
                        if (result.getResultCode() == 1 && result.getData() != null) {
                            //  支付宝支付
                            AliPayHelper.pay(result.getData().getOrderInfo(), RechargeActivity.this, alipayResult);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        //
                        ToastUtil.showToast(mContext, getString(R.string.pay_failed));
                    }
                });

    }


    /**
     * 设置hint字体大小
     *
     * @param editText
     * @param hintText
     * @param size
     */
    public static void setEditTextHintSize(EditText editText, String hintText, int size) {
        SpannableString ss = new SpannableString(hintText);//定义hint的值
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true);//设置字体大小 true表示单位是sp
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        editText.setHint(new SpannedString(ss));
    }


    public static void setEditTextTextSize(EditText editText, String hintText, int size) {
        SpannableString ss = new SpannableString(hintText);//定义hint的值
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true);//设置字体大小 true表示单位是sp
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        editText.setText(new SpannedString(ss));
        editText.setSelection(editText.length());
    }
}
